package com.chenyq.rabbitmq.workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 *
 * @author chenyq
 * @date 2023/11/29
 */

public class Producer {

    private static final String QUEUE = "workQueue";

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置主机地址
        factory.setHost("127.0.0.1");
        // 设置端口号
        factory.setPort(5672);
        // 设置虚拟主机
        factory.setVirtualHost("/");
        // 设置用户名
        factory.setUsername("admin");
        // 设置密码
        factory.setPassword("123456");
        // 创建连接
        Connection connection = null;
        // 创建通道
        Channel channel = null;
        try {
            // 创建连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();
            // 声明队列
            channel.queueDeclare(QUEUE, true, false, false, null);

            // 循环1000次
            for (int i = 0; i < 1000; i++) {
                // 拼接消息
                String msg = "你有新的通知待查看: " + i;
                // 发布消息
                channel.basicPublish("",QUEUE,null,msg.getBytes());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                // 关闭通道
                if (channel != null & connection != null) {
                    channel.close();
                    connection.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    }

}
